package mailSendService.module;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileUtil {
    /**
     * 获取文件的byte[] 数据
     */
    public static byte[] localBufferRead(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        try {
            FileInputStream inputFile = new FileInputStream(file);
            FileChannel fileChannel = inputFile.getChannel(); //文件输入stream nio
            ByteBuffer buffer = ByteBuffer.allocate(((int) file.length())); //使用Byte buffer 创建
            fileChannel.read(buffer);
            inputFile.close();
            return buffer.array();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void localBufferWrite(byte[] buffer, String targetPath){
        mkDirs(targetPath); //创建文件夹
        try {
            FileOutputStream out = new FileOutputStream(targetPath);
            out.write(buffer);
            File file = new File(targetPath); //读取写入的文件，设置文件属性
            file.setWritable(true, false);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void mkDirs(String path){
      File file = new File(path);
      if (file.exists()){
          if (file.isDirectory()){
              file.mkdirs();
          }else{
              mkDirs(path.substring(0, path.lastIndexOf("/")));
          }
      }
    }
}
